#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import os.path

import yaml

from api.gitee import Gitee
from core import extract_repo_pull, ProcessRecords
from exception import RequestError
from logger import logger


class Comment:
    """
    Add a comment to the specified pr
    """

    def __init__(self, pr_url, message, process, users):
        self.pr = pr_url
        self.users = users
        self.process = process
        self.message = message

    def comment_message(self):
        """
        Add a comment to the specified pr
        """
        notify_users = self._add_notify_users(self.users)
        # When "message" specified, comment the "message"
        if self.message:
            notify_message = self.message + notify_users
        else:
            process_message = self._get_process_message()
            if self.process:
                notify_message = process_message.get(self.process)
            else:
                current_result = self._get_current_process_from_file()
                current_process = current_result.get("current_progress")
                notify_message = process_message.get(current_process) if current_process else ""
            notify_message = notify_message + notify_users if notify_message else ""

        if notify_message:
            self._add_comment_to_pr(notify_message)
        else:
            logger.warning(f"Add comment content is empty")

    @staticmethod
    def _add_notify_users(users):
        """
        Add users who need to be notified
        :param users: users who need to be notified
        :return: string  e.g. @userA,@userB,@userC
        """
        if not users:
            return ""
        return "@" + ",@".join(users)

    def _add_comment_to_pr(self, message):
        """
        add comment to pr
        :param message: the content of the comment
        :return: None
        """
        repo_name, pr_num = extract_repo_pull(self.pr)
        gitee_api = Gitee(repo=repo_name)
        response = gitee_api.create_pr_comment(number=pr_num, body=message)

        if not response:
            raise RequestError(f"Failed to comment content {message} to {self.pr}")

    def _get_process_message(self):
        """
        Parse the echo information configuration file of the execution process
        :return: information of the execution process(dict)
        """
        current_path = os.path.dirname(os.path.relpath(self.__file__))
        message_file = os.path.join(os.path.dirname(current_path), "conf/process_message.yaml")
        try:
            with open(message_file, 'r') as msg_file:
                process_message = yaml.safe_load(msg_file)
                return process_message
        except yaml.YAMLError as error:
            logger.error(f"Parsing file process_message.yaml failed: {error}")
            return dict()

    def _get_current_process_from_file(self):
        """
        Get the current execution step from the result log file
        :return: dict e.g.
        {
        "current_progress": "single_build_check",
        "next_progress": [
            "single_install_check",
            "compare_check",
            "multi_build_check",
            "multi_install_check"
            ]
        }
        """
        repo_name, pr_num = extract_repo_pull(self.pr)
        result_file_instance = ProcessRecords(package=repo_name, pr=pr_num)
        return result_file_instance.progress
